package etp.client.gui;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;

import etp.client.Etp;
import etp.client.Recurso;
import etp.client.Tarefa;
import etp.client.Logger.LoggerType;
import etp.client.rpc.ResourceAdminService;
import etp.client.rpc.ResourceAdminServiceAsync;

public class TarefaRespForm extends Composite implements StatefullForm{

	private Label lblErro = new Label();
	
	private Label lblResponsavel = new Label("Respons\u00e1vel:");
	
	private ListBox cmbResponsavel = new ListBox();
	
	private ResourceAdminServiceAsync service = GWT.create(ResourceAdminService.class);
	
	private Tarefa tarefa;
	
	private List<Recurso> desenvolvedores;
	
	public TarefaRespForm(){
		
		this.lblErro.addStyleName("ErrorLabel");
	
		FlexTable pnlMain = new FlexTable();
	
		pnlMain.setWidget(0, 0, this.lblErro);
		
		pnlMain.setWidget(1, 0, this.lblResponsavel);
		
		pnlMain.setWidget(1, 1, this.cmbResponsavel);
		
		pnlMain.getFlexCellFormatter().setColSpan(0, 0, 2);
		
		this.initWidget(pnlMain);
	}

	public Tarefa getTarefa() {
		return tarefa;
	}

	public void setTarefa(Tarefa tarefa) {
		this.tarefa = tarefa;
		
		this.loadDesenvolvedores();
	}
	
	public void clean(){
		this.cmbResponsavel.setSelectedIndex(0);	
		this.lblErro.setText("");
	}
	
	public void updateTarefa(Tarefa t){
		
		int selectedIndex = this.cmbResponsavel.getSelectedIndex();
		
		if(selectedIndex != -1)
			t.setResponsavel(
					this.desenvolvedores.get(selectedIndex).getCod());
	}
	
	public void updateFromTarefa(){
		
		int selectedIndex = -1;
		
		int i = 0;
		for(Recurso r : this.desenvolvedores){
			
			if(r.getCod().equals(this.tarefa.getResponsavel())){
				selectedIndex=i;
				break;
			}
			i++;
			
		}
		
		this.cmbResponsavel.setSelectedIndex(selectedIndex);
	}

	public void loadDesenvolvedores(){
		
		this.service.list(new AsyncCallback<List<Recurso>>() {
			
			@Override
			public void onSuccess(List<Recurso> result) {
				TarefaRespForm.this.desenvolvedores = result;
				
				TarefaRespForm.this.cmbResponsavel.clear();
				
				for(Recurso r : result){
					TarefaRespForm.this.cmbResponsavel.addItem(r.getEmail());
				}
				
				TarefaRespForm.this.updateFromTarefa();
			}
			
			@Override
			public void onFailure(Throwable caught) {
				Etp.logger.show(caught.getMessage(), LoggerType.ERROR);	
			}
		});
		
	}
	
	public void validate(){
		if(this.desenvolvedores.size() == 0 || this.cmbResponsavel.getSelectedIndex() < 0){
			this.lblErro.setText("Nenhum desenvolvedor atribuido.");
			return;
		}
		
		this.lblErro.setText("");
	}
	
	@Override
	public int getFormState() {
		
		this.validate();

		if(this.lblErro.getText().length() == 0){
			return StatefullForm.OK;
		}
		
		return StatefullForm.ERRO;
	}
	
}
